package com.jiaozi.core.exception;

import com.jiaozi.base.utils.bean.R;
import com.jiaozi.base.utils.bean.enums.REnum;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalJiaoZiException {

    @ExceptionHandler
    public R customException(Exception ex) {
        log.error("异常信息：{}", ex.toString());
        ex.printStackTrace();
        switch (ex ){
            case CommonException ignored: //自定义通用异常
                CommonException commonException= (CommonException) ex;
                return R.error(commonException.getREnum(), commonException.getExceptionMessage());

            case InternalAuthenticationServiceException ignored:
                InternalAuthenticationServiceException internalAuthenticationServiceException= (InternalAuthenticationServiceException) ex;
                boolean b = internalAuthenticationServiceException.getCause() instanceof CommonException;
                if(b){
                     commonException= (CommonException)  internalAuthenticationServiceException.getCause();
                    return R.error(commonException.getREnum(), commonException.getExceptionMessage());
                }
                break;

            case AccountExpiredException ignored:

                return R.error(REnum.LOGIN_ERROR,ex.getMessage());
            case DisabledException ignored:

                return R.error(REnum.LOGIN_ERROR,ex.getMessage());



            case MethodArgumentNotValidException ignored:// controller参数校验异常
                MethodArgumentNotValidException methodArgumentNotValidException= (MethodArgumentNotValidException) ex;
                BindingResult exceptions = methodArgumentNotValidException.getBindingResult();
                // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
                if (exceptions.hasErrors()) {
                    List<ObjectError> errors = exceptions.getAllErrors();
                    if (!errors.isEmpty()) {
                        // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                        FieldError fieldError = (FieldError) errors.get(0);
                        return R.error(REnum.PARAM_ERROR,fieldError.getDefaultMessage());
                    }
                }
                return R.error(methodArgumentNotValidException.getMessage());
            default:
                return R.error(REnum.ERROR,ex.getMessage());

        }
        return R.error(REnum.ERROR,ex.getMessage());

    }
}
